package com.qf.service.impl;

import com.qf.dao.GoodsRepository;
import com.qf.dao.ShopCartMapper;
import com.qf.pojo.entity.Goods;
import com.qf.pojo.entity.ShopCart;
import com.qf.pojo.resp.BaseResp;
import com.qf.pojo.resp.CartGoodsResp;
import com.qf.pojo.resp.CartResp;
import com.qf.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @ClassName ShopCartServiceImpl
 * @Description TODO
 * @Author Windy
 * @Date 2022/9/28 20:38
 * @Version 1.0
 **/
@Service
public class ShopCartServiceImpl implements ShopCartService {

    @Autowired
    ShopCartMapper shopCartMapper;

    @Autowired
    GoodsRepository goodsRepository;

    @Override
    public BaseResp findByUser(int id) {
        List<CartGoodsResp> cartUser = shopCartMapper.findCartUser(id);
        double total=0;
        for (CartGoodsResp resp : cartUser) {
            total+= resp.getMoney();
        }
        CartResp cartResp = new CartResp();
        cartResp.setGoodsList(cartUser);
        cartResp.setTotalPrice(total);
        return new BaseResp(200,"用户购物车数据查询成功",cartResp);
    }

    //向购物车添加商品
    @Override
    public BaseResp upToCart(int uid, int gid) {
        //先获取连接判断购物车是否存在该商品
        ShopCart cartGoods = shopCartMapper.getCartGoods(uid, gid);
        //获取商品
        Goods byId = goodsRepository.findById(gid);
        if (cartGoods != null) {
            cartGoods.setGoodsNumber(cartGoods.getGoodsNumber()+1);
            cartGoods.setGoodsMoney(byId.getGoodsPrice()*cartGoods.getGoodsNumber());
            //购物车中存在该商品
            shopCartMapper.updateAddCart(cartGoods);
        }else {
            //购物车中没有该商品
            ShopCart shopCart = new ShopCart();
            shopCart.setGoodsId(gid);
            shopCart.setUserId(uid);
            shopCart.setGoodsNumber(1);
            shopCart.setGoodsMoney(byId.getGoodsPrice());
            shopCartMapper.addCart(shopCart);
        }
        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp divCart(int uid, int gid) {

        //获取当前购物车中的数据
        ShopCart cartGoods = shopCartMapper.getCartGoods(uid, gid);
        //获取商品
        Goods byId = goodsRepository.findById(gid);

        if (cartGoods.getGoodsNumber()>=2) {
            //如果商品数量大于2则让商品数量减1
            cartGoods.setGoodsNumber(cartGoods.getGoodsNumber()-1);
            cartGoods.setGoodsMoney(byId.getGoodsPrice()*cartGoods.getGoodsNumber());

            //更新购物车中的数据
            shopCartMapper.updateAddCart(cartGoods);
        }else {
            //如果商品数量为1则删除该商品
            shopCartMapper.delCartGoods(uid,gid);
        }
        return new BaseResp().SUCCESS();
    }

    @Override
    public BaseResp cleanCart(int uid) {
        shopCartMapper.cleanCaet(uid);
        return new BaseResp().SUCCESS();
    }
}
